const {
  src,
  dest,
  series,
  parallel,
  watch
} = require('gulp')
const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()
const del = require('del')
const bs = require('browser-sync').create()

// 是否是生产环境
const isPro = process.argv[process.argv.length - 1] !== 'dev'

const config = {
  input: 'src', //入口文件目录
  output: 'dist', //生成文件目录
  temp:'.temp'//文件临时目录
}


const _src = (path, base) => {
  return src(`${config.input}/${path}`, {
    base: base || config.input
  })
}

// 清除上次生成的文件
const clean = () => {
  return del([config.temp,config.output])
}

// 处理js文件
const script = () => {
  return _src('assets/**/*.js')
    .pipe(plugins.babel({
      presets: ['@babel/preset-env']
    }))
    .pipe(plugins.if(isPro, plugins.uglify()))
    .pipe(dest(config.temp))
}

// 处理scss文件
const style = () => {
  return _src('assets/styles/*.scss')
    .pipe(plugins.sass({
      outputStyle: isPro ? 'compressed' : 'nested'
    }))
    .pipe(dest(config.temp))
}
const menus = [{
    name: 'Home',
    icon: 'aperture',
    link: 'index.html'
  },
  {
    name: 'Features',
    link: 'features.html'
  },
  {
    name: 'About',
    link: 'about.html'
  },
  {
    name: 'Contact',
    link: '#',
    children: [{
        name: 'Twitter',
        link: 'https://twitter.com/w_zce'
      },
      {
        name: 'About',
        link: 'https://weibo.com/zceme'
      },
      {
        name: 'divider'
      },
      {
        name: 'About',
        link: 'https://github.com/zce'
      }
    ]
  }
]
// 处理html
const page = () => {
  return _src('*.html')
    .pipe(plugins.swig({
      data: {
        pkg: require('./package.json'),
        date: new Date(),
        menus: menus
      }
    }))
    // .pipe(
    //   plugins.if(isPro, plugins.htmlmin({
    //     collapseWhitespace: true,
    //     minifyCSS: true,
    //     minifiJS: true
    //   }))
    // )
    .pipe(dest(config.temp))
}

// 处理 图片、字体文件
const imageAndFont = () => {
  return _src('assets/{images,fonts}/*') //处理images、fonts下的所有文件
    .pipe(plugins.imagemin())
    .pipe(dest(config.output))
}
//处理public目录
const public = () => {
  return src('public/**', {
      base: config.input
    })
    .pipe(plugins.imagemin())
    .pipe(dest(config.output))
}

// 处理引用文件  如bootstrap
const useref = () => {
  return src(`${config.temp}/*.html`, {
      base: config.temp
    })
    .pipe(plugins.useref({
      searchPath: [config.temp, '.']
    }))
    .pipe(
      plugins.if(/\.html$/,
        plugins.htmlmin({
          collapseWhitespace: true,
          minifyCSS: true,
          minifiJS: true
        })
      )
    )
    .pipe(plugins.if(/\.js$/,plugins.uglify()))
    .pipe(dest(config.output))
}

const serve = () => {
  // 监听文件变化并处理
  watch(`${config.input}/assets/styles/*.scss`, style)
  watch(`${config.input}/assets/**/*.js`, script)
  watch(`${config.input}/*.html`, page)

  //开发环境不需要处理图片等文件的压缩，直接刷新
  watch([
    `${config.input}/assets/{images,fonts}/*`,
    `${config.input}/public/**`
  ], bs.reload)

  bs.init({
    open: false, //启动时是否打开浏览器
    notify: false,
    files: `${config.temp}/**`, //监听文件变化
    server: {
      baseDir: [config.temp, 'src', '.'] //文件加载地址（先加载dist目录，如果dist目录不存在该文件，会到src目录文件,src找不到，会到当前目录）
    }
  })
}

const compile = parallel(script, style, page)
const build = series(
  clean,
  parallel(
    series(compile, useref),
    imageAndFont,
    public
  )
)
const dev = series(compile, serve)
module.exports = {
  script,
  style,
  page,
  imageAndFont,
  public,
  useref,
  clean,
  compile,
  build,
  dev
}
